<template>
  <div>
    <div class="ivu-userHeader">
      <div v-if="selectItemArr.length" class="ivu-action">
        <span>
          <a
            v-hasC="{
              name: 'rbac-member-update',
              flag: 'v1/rbac/member/update',
            }"
            @click="handleAdd('edit')"
            >编辑</a
          >
        </span>
        <span
          v-hasC="{
            name: 'rbac-member-allocation',
            flag: 'v1/rbac/member/allocation',
          }"
        >
          <a v-if="disable" style="cursor: not-allowed;color: #787878;"
            >分配角色和职能</a
          >
          <a v-else @click="handleAllocation">分配角色和职能</a>
        </span>
        <span
          v-hasC="{
            name: 'rbac-member-department-manager',
            flag: 'v1/rbac/member/department-manager',
          }"
        >
          <a style="cursor: not-allowed;color: #787878;" v-if="disable"
            >设为部门管理员</a
          >
          <a v-else @click="handleManager">设为部门管理员</a>
        </span>
        <span
          v-hasC="{
            name: 'rbac-member-cancel-leader',
            flag: 'v1/rbac/member/cancel-leader',
          }"
        >
          <a style="cursor: not-allowed;color: #787878;" v-if="disable"
            >取消部门管理员</a
          >
          <a v-else @click="cancelManager">取消部门管理员</a>
        </span>
        <span>
          <a
            v-hasC="{
              name: 'rbac-member-reset-password',
              flag: 'v1/rbac/member/reset-password',
            }"
            @click="resetPassWord"
            >重置密码</a
          >
        </span>
        <span>
          <a
            v-hasC="{
              name: 'v1-rbac-member-delete-project',
              flag: 'v1/rbac/member/delete-project',
            }"
            @click="resetProgect"
            >从项目中移除</a
          >
        </span>
      </div>
      <div inline v-else>
        <Row :gutter="16">
          <Col span="5">
            <Select
              placeholder="角色筛选"
              v-model="formData.role_id"
              clearable
              @on-change="changeRole"
            >
              <Option
                v-for="item in roleList"
                :key="item.id"
                :value="item.id"
                >{{ item.label }}</Option
              >
            </Select>
          </Col>

          <Col span="7">
            <Input
              @on-enter="keyEnter"
              v-model="formData.keyword"
              placeholder="请输入姓名或手机号"
              :clearable="true"
              @on-clear="clearKeyWord"
            />
          </Col>
          <Col span="12">
            <div style="display: flex;justify-content: flex-end;">
              <Button
                v-hasC="{
                  name: 'rbac-member-create',
                  flag: 'v1/rbac/member/create',
                }"
                type="primary"
                @click="handleAdd('add')"
                >新建用户</Button
              >
            </div>
          </Col>
        </Row>
      </div>
    </div>
    <Table
      highlight-row
      :columns="columns"
      :data="list"
      :loading="loading"
      ref="table"
      :max-height="650"
      @on-selection-change="changeCheckBox"
    >
      <template slot="realname" slot-scope="{ row }">
        <div style="display: flex;align-items: center;">
          <div>{{ row.realname }}</div>
          <Icon
            v-if="row.is_department_leader === '1'"
            style="margin-left: 10px;"
            size="20"
            type="ios-person"
          />
        </div>
      </template>

      <template slot="role_name_arr" slot-scope="{ row }">
        <div style="width:100%;display: flex;flex-wrap: wrap;">
          <template v-for="(item, index) in row.role_name_arr">
            <Tag v-if="item !== ''" color="green">{{ item }}</Tag>
          </template>
          <!-- <span v-if="row.role_name_arr.length==0" style="color:#f00">*****</span> -->
        </div>
      </template>
      <template slot="competency_name_arr" slot-scope="{ row }">
        <div style="width:100%;display: flex;flex-wrap: wrap;">
          <template v-for="(item, index) in row.competency_name_arr">
            <Tag v-if="item !== ''" color="green">{{ item }}</Tag>
          </template>
        </div>
      </template>
    </Table>
    <div class="ivu-mt ivu-text-center" slot="footer">
      <Page
        :total="total"
        :current.sync="formData.page"
        :page-size-opts="options"
        show-total
        @on-change="changePage"
        show-elevator
        show-sizer
        @on-page-size-change="changePageSize"
      ></Page>
    </div>
    <Modal
      :title="addEdit ? '新增' : '编辑'"
      width="680"
      v-model="createModel"
      :mask-closable="false"
      draggable
    >
      <Form ref="addForm" :model="formItem" :label-width="80" :rules="addRule">
        <Row :gutter="12">
          <Col span="12">
            <FormItem label="姓名" prop="name">
              <Input v-model="formItem.name" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="性别">
              <RadioGroup v-model="formItem.gender">
                <Radio label="男">男</Radio>
                <Radio label="女">女</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="手机号" prop="phone">
              <Input v-model="formItem.phone" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="岗位">
              <Input v-model="formItem.post" />
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="部门" prop="department">
              <TreeSelect
                v-model="formItem.department"
                :data="departmentList"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel">取消</Button>
        <Button type="primary" :loading="remarksloading" @click="handleComfirm"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal
      v-model="allocationModel"
      title="职能和角色分配"
      :mask-closable="false"
      draggable
    >
      <div style="display: flex;">
        <div style="width: 88px;">选中人员：</div>
        <p>{{ selectFb }}</p>
      </div>
      <Divider></Divider>
      <Form>
        <FormItem label="职能：" :label-width="70">
          <RadioGroup v-model="fp_role_competency.competency">
            <Radio
              v-for="(item, index) in competencyList"
              :label="+item.id"
              :key="index"
              >{{ item.competency_name }}
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="角色："
          :label-width="70"
          style="max-height: 400px;overflow-y: auto;"
        >
          <CheckboxGroup v-model="fp_role_competency.role">
            <Checkbox
              v-for="(item, index) in checkBoxDisabled"
              :label="+item.id"
              :key="index"
              :disabled="item.disabled"
            >
              {{ item.name }}</Checkbox
            >
          </CheckboxGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="allocationModel = false">取消</Button>
        <Button type="primary" :loading="remarksloading" @click="handlerFpBtn"
          >确定</Button
        >
      </div>
    </Modal>
    <Modal v-model="allEdit" title="批量编辑" :mask-closable="false">
      <Form :label-width="130">
        <FormItem label="选择批量字段：">
          <Select
            placeholder="请选择批量操作字段"
            v-model="allEditClassify"
            multiple
            clearable
            @on-change="changeAllEdit"
          >
            <Option
              v-for="(item, index) in allEditList"
              :key="item"
              :value="item"
              >{{ item }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="性别:" v-show="computeIsSHow('性别')">
          <RadioGroup v-model="allEditForm.xb">
            <Radio label="男">男</Radio>
            <Radio label="女">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="部门" v-show="computeIsSHow('部门')">
          <TreeSelect
            v-model="allEditForm.bm"
            :data="departmentList"
            placeholder="请选择部门"
          />
        </FormItem>
        <FormItem label="岗位" v-show="computeIsSHow('岗位')">
          <Input v-model="allEditForm.gw" placeholder="请选择岗位" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="allEdit = false">取消</Button>
        <Button type="primary" :loading="remarksloading" @click="handlerAllEdit"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  getMemberList,
  getMemberInfo,
  addMember,
  getDepartmentList,
  editMember,
  fpMember,
  resetPassword,
  setManager,
  getPersonalDetail,
  cancelManager,
  deleteProject,
} from "@/api/TApi/index.js";
export default {
  props: ["department_id", "pid", "departmentLists"],
  data() {
    const validatePhone = (rule, value, callback) => {
      var reg = /^[1][0-9]{10}$/;
      if (!reg.test(value)) {
        callback(new Error("请填写正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      //
      oldDeptId: "",
      allEditClassify: [],
      allEditList: ["性别", "部门", "岗位"],
      allEditForm: {
        xb: "",
        bm: "",
        gw: "",
      },
      //
      // 分配职能表单
      fp_role_competency: {
        role: [],
        competency: "",
      },
      disableArr: [],
      defaultArrList: [],
      //
      //
      allEdit: false,
      //
      formData: {
        page: 1,
        size: 10,
        keyword: "",
        role_id: "",
      },
      //
      departmentId: "",
      //
      departmentList: [],
      //
      total: 0,
      //
      list: [],
      duty: "普通员工",
      role: [],
      allocationModel: false,
      userAction: false,
      roleList: [],
      selectItemArr: [],
      remarksloading: false,
      competencyList: [],
      fpRoleList: [],
      //
      addEdit: true,
      createModel: false,
      loading: false,
      formItem: {
        name: "",
        phone: "",
        gender: "",
        post: "",
        department: "",
      },
      //
      addRule: {
        name: { required: true, message: "请输入姓名", trigger: "blur" },
        phone: {
          validator: validatePhone,
          required: true,
          trigger: "blur",
        },
        department: {
          required: true,
          message: "请选择部门",
          trigger: "change",
        },
      },
      //
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: "姓名",
          slot: "realname",
          width: 140,
        },
        {
          title: "电话",
          key: "mobile",
          width: 130,
        },
        {
          title: "部门",
          key: "department_name",
          width: 120,
        },
        {
          title: "职能",
          slot: "competency_name_arr",
          width: 170,
        },
        {
          title: "角色",
          slot: "role_name_arr",
          minWidth: 150,
        },
        {
          title: "最近登录时间",
          key: "last_time",
          width: 150,
        },
      ],
      userList: [],
      creating: true,
      updateIndex: -1,
      projects_arr: [],
      options: [10, 20, 30, 100, 200],
    };
  },
  computed: {
    checkBoxDisabled() {
      let arr = [];
      this.roleList.forEach((ee) => {
        let obj = {
          ...ee,
        };
        let flag = this.disableArr.find((vv) => {
          return vv == ee.id;
        });
        if (flag) {
          obj.disabled = true;
        }
        arr.push(obj);
      });
      return arr;
    },
    computeIsSHow(value) {
      return function(value) {
        return this.allEditClassify.filter((ee) => {
          return ee === value;
        }).length;
      };
    },
    // 选中人员时候分配角色和职能展示的名字
    selectFb() {
      return this.selectItemArr
        .map((ee) => {
          return ee.realname;
        })
        .join("、");
    },
    selectIds() {
      return this.selectItemArr
        .map((ee) => {
          return ee.id;
        })
        .join(",");
    },
    disable() {
      return this.pid == "-1";
    },
  },
  methods: {
    handlerAllEdit() {
      let params = {};
      for (let key in this.allEditForm) {
        if (this.allEditForm[key]) {
          params[key] = this.allEditForm[key];
        }
      }
      if (JSON.stringify(params) === "{}") {
        this.$Message.warning("请至少操作一项数据");
        return false;
      }
      let paramsData = {};
      if (params.xb) {
        paramsData.gender = params.xb === "男" ? 1 : 2;
      }
      if (params.bm) {
        paramsData.department_id = params.bm;
      }
      if (params.gw) {
        paramsData.profession_name = params.gw;
      }
      paramsData.ids = this.selectIds;
      if (paramsData.department_id) {
        this.$Modal.confirm({
          title: "温馨提示",
          content: "修改部门所涉及用户数据将全部进入公海，是否继续提交",
          onOk: () => {
            this.remarksloading = true;
            editMember(paramsData)
              .then((res) => {
                this.$Message.success("批量编辑人员成功");
                this.getData();
                this.$emit("changeKeys");
                this.remarksloading = false;
                this.allEdit = false;
              })
              .catch(() => {
                this.remarksloading = false;
              });
          },
        });
      } else {
        editMember(paramsData)
          .then((res) => {
            this.$Message.success("批量编辑人员成功");
            this.getData();
            this.$emit("changeKeys");
            this.remarksloading = false;
            this.allEdit = false;
          })
          .catch(() => {
            this.remarksloading = false;
          });
      }
    },
    // 点击取消
    cancel() {
      this.createModel = false;
    },
    // 选中项
    changeCheckBox(arr) {
      // console.log(arr,'arr');
      this.selectItemArr = arr;
    },
    // 修改页码
    changePage(value) {
      this.formData.page = value;
      this.getData();
    },
    changePageSize(value) {
      this.formData.page = 1;
      this.formData.size = value;
      this.getData();
    },
    // 清楚关键字
    clearKeyWord() {
      this.getData();
    },
    // 关键字搜索
    keyEnter() {
      this.formData.role_id = "";
      this.getData();
    },
    // 点击分配确定
    handlerFpBtn() {
      if (
        this.fp_role_competency.competency == "" &&
        !this.fp_role_competency.role.length
      ) {
        this.$Message.warning("请至少分配一项");
        return;
      }
      // console.log(this.fp_role_competency.role)
      // console.log(this.defaultArrList)

      let role_ids = this.fp_role_competency.role
        .filter((ee) => {
          return this.defaultArrList.indexOf(ee) < 0;
        })
        .join(",");
      let params = {
        ids: this.selectIds,
        role_ids,
        competency_id: this.fp_role_competency.competency,
        department_id: this.department_id,
      };
      this.remarksloading = true;
      fpMember(params)
        .then((res) => {
          this.$Message.success("分配成功");
          this.allocationModel = false;
          this.getData();
          this.remarksloading = false;
        })
        .catch(() => {
          this.remarksloading = false;
        });
    },
    // 切换角色
    changeRole() {
      this.getData();
    },
    // 新增或编辑确定按钮
    handleComfirm() {
      switch (this.addEdit) {
        case true:
          {
            this.$refs.addForm.validate((valid) => {
              if (valid) {
                let params = {
                  name: this.formItem.name,
                  mobile: this.formItem.phone,
                  gender: this.formItem.gender
                    ? this.formItem.gender === "男"
                      ? 1
                      : 2
                    : 0,
                  profession_name: this.formItem.post,
                  department_id: this.formItem.department,
                };
                this.remarksloading = true;
                addMember(params)
                  .then((res) => {
                    this.$Message.success("新增人员成功");
                    this.getData();
                    this.createModel = false;
                    this.$emit("changeKeys");
                    this.remarksloading = false;
                  })
                  .catch(() => {
                    this.remarksloading = false;
                  });
              }
            });
          }
          break;
        case false:
          {
            let params = {
              name: this.formItem.name,
              mobile: this.formItem.phone,
              gender: this.formItem.gender
                ? this.formItem.gender === "男"
                  ? 1
                  : 2
                : 0,
              profession_name: this.formItem.post,
              department_id: this.formItem.department,
              ids: this.selectItemArr[0].id,
            };
            if (this.oldDeptId != this.formItem.department) {
              this.$Modal.confirm({
                title: "温馨提示",
                content: "修改部门所涉及用户数据将全部进入公海，是否继续提交",
                onOk: () => {
                  this.remarksloading = true;
                  editMember(params)
                    .then((res) => {
                      this.$Message.success("编辑人员成功");
                      this.getData();
                      this.$emit("changeKeys");
                      this.createModel = false;
                      this.remarksloading = false;
                    })
                    .catch(() => {
                      this.remarksloading = false;
                    });
                },
              });
            } else {
              this.remarksloading = true;
              editMember(params)
                .then((res) => {
                  this.$Message.success("编辑人员成功");
                  this.getData();
                  this.$emit("changeKeys");
                  this.createModel = false;
                  this.remarksloading = false;
                })
                .catch(() => {
                  this.remarksloading = false;
                });
            }
          }
          break;
      }
    },

    // 初始化新增或编辑部门下拉信息
    // _getDepartmentList() {
    //   getDepartmentList().then((res) => {
    //     this.departmentList = this.handlerArr(res);
    //   });
    // },
    // 多选编辑时选择编辑项目
    changeAllEdit(value) {
      let obj = {
        性别: "xb",
        部门: "bm",
        岗位: "gw",
      };
      value.forEach((ee) => {
        for (let key in obj) {
          if (key !== ee) {
            this.allEditForm[obj[key]] = "";
          }
        }
      });
    },
    cancelManager() {
      let flag = this.selectItemArr.every((ee) => {
        return ee.is_department_leader === "1";
      });
      if (flag) {
        this.$Modal.confirm({
          title: "取消部门管理员",
          content: "请确认是否将选中的用户取消部门管理员,取消后职能相应取消",
          onOk: () => {
            cancelManager({
              ids: this.selectIds,
            }).then((res) => {
              this.$Message.success("取消部门管理员成功");
              this.getData();
            });
          },
        });
      } else {
        this.$Message.warning("当前选中人员中存在非部门管理人员");
      }
    },
    // 初始化数据
    getData() {
      this.loading = true;
      let params = {
        page: this.formData.page,
        pageSize: this.formData.size,
        keyword: this.formData.keyword,
        department_id: this.department_id,
        role_id:
          this.formData.role_id === undefined ? "" : this.formData.role_id,
      };
      getMemberList(params).then((res) => {
        this.loading = false;
        this.total = res.total;
        this.list = res.list;
        this.selectItemArr = [];
      });
    },
    // 处理数组
    handlerArr(arr) {
      arr.forEach((ee) => {
        ee.title = ee.label;
        ee.expand = true;
        ee.children && this.handlerArr(ee.children);
      });
      return arr;
    },
    handleAdd(type) {
      this.$refs.addForm.resetFields();
      this.formItem.gender = "";
      this.formItem.post = "";
      switch (type) {
        case "add":
          {
            this.addEdit = true;
            this.formItem.department = this.departmentId;
            this.createModel = true;
          }
          break;
        case "edit":
          {
            if (this.selectItemArr.length > 1) {
              this.allEdit = true;
              (this.allEditClassify = []),
                (this.allEditForm = {
                  xb: "",
                  bm: "",
                  gw: "",
                });
            } else {
              this.addEdit = false;
              this.createModel = true;
              let data = this.selectItemArr[0];
              this.formItem.post =
                data.profession_name == 0 ? "" : data.profession_name;
              this.formItem.name = data.realname;
              if (data.gender === "1") {
                this.formItem.gender = "男";
              } else if (data.gender === "2") {
                this.formItem.gender = "女";
              } else {
                this.formItem.gender = "";
              }
              this.formItem.phone = data.mobile;
              this.findDepartmentId(this.departmentList, data.department_name);
              this.formItem.department = this.selectItemArr[0].pidd;
              this.oldDeptId = this.selectItemArr[0].pidd;
            }
          }
          break;
      }
    },
    // 编辑时根据row的部门名称寻找id
    findDepartmentId(arr, title) {
      for (let i = 0; i < arr.length; i++) {
        let item = arr[i];
        if (item.label == title) {
          this.selectItemArr[0].pidd = item.id;
          return false;
        } else if (item.children && item.children.length) {
          this.findDepartmentId(item.children, title);
        }
      }
    },
    handleAllocation() {
      getPersonalDetail({
        department_id: this.department_id,
        ids: this.selectIds,
      }).then((res) => {
        this.fp_role_competency.role = Array.from(
          new Set([
            ...res.department_role_id_arr.concat(res.member_role_id_arr),
          ])
        );
        this.defaultArrList = res.department_role_id_arr;
        this.fp_role_competency.competency = res.competency_id;
        this.disableArr = res.department_role_id_arr;
      });
      this.allocationModel = true;
    },

    handleManager() {
      this.$Modal.confirm({
        title: "部门管理员设置",
        content: "请确认是否将选中的用户设为管理员",
        onOk: () => {
          setManager({
            ids: this.selectIds,
          }).then((res) => {
            this.$Message.success("设置成功");
            this.getData();
          });
        },
      });
    },
    resetPassWord() {
      this.$Modal.confirm({
        title: "重置密码",
        content:
          "是否对选中的用户做密码重置操作<br>重置后的密码为：<b>jgwl123456</b>",
        onOk: () => {
          resetPassword({
            ids: this.selectIds,
          }).then((res) => {
            this.$Message.success("重置成功");
            this.getData();
          });
        },
      });
    },
    resetProgect() {
      this.$Modal.confirm({
        title: "从项目中移除",
        content:
          '<p style="font-size:18px">当前用户将从该项目中删除，不在拥有该项目权限，所涉及用户数据将全部进入公海</p><p style="color:#f00;margin-top:8px">（该功能相当于将用户从当前项目中删除）</p>',
        onOk: () => {
          deleteProject({
            ids: this.selectIds,
          }).then((res) => {
            this.$Message.success("删除成功");
            this.getData();
          });
        },
      });
    },
  },
  mounted() {
    // this._getDepartmentList();
  },
  watch: {
    department_id: {
      handler(value) {
        if (value !== "") {
          this.departmentId = value;
          this.formData.role_id = "";
          this.formData.keyword = "";
          this.formData.page = 1;
          getMemberInfo({ department_id: value }).then((res) => {
            this.roleList = res.role;
            this.competencyList = res.competency;
            this.fpRoleList = res.role;
            this.selectItemArr = [];
          });
          this.getData();
          // this._getDepartmentList();
        }
      },
      immediate: true,
    },
    departmentLists: {
      handler(value) {
        this.departmentList = this.handlerArr(
          JSON.parse(JSON.stringify(value))
        );
      },
    },
  },
};
</script>
<style scoped>
.ivu-userHeader {
  height: 50px;
}

.ivu-action {
  line-height: 40px;
}

.ivu-action span {
  margin: 0 10px;
}

/deep/.ivu-table-wrapper {
  overflow: visible !important;
}
/deep/.ivu-tag {
  height: auto !important;
}
</style>
